import { useIntl } from '@umijs/max';
import { Button, message, notification } from 'antd';
import defaultSettings from '../config/defaultSettings';

const { pwa } = defaultSettings;
const isHttps = document.location.protocol === 'https:';

/**
 * 清除浏览器缓存
 */
const clearCache = () => {
  if (window.caches) {
    caches.keys()
      .then((keys) => {
        keys.forEach((key) => caches.delete(key));
      })
      .catch((e) => console.log('清除缓存失败:', e));
  }
};

// PWA 功能处理
if (pwa) {
  // 离线状态提示
  window.addEventListener('sw.offline', () => {
    message.warning(useIntl().formatMessage({ id: 'app.pwa.offline' }));
  });

  // 服务工作线程更新提示
  window.addEventListener('sw.updated', (event: Event) => {
    const e = event as CustomEvent;
    
    // 重载服务工作线程
    const reloadSW = async () => {
      const worker = e.detail?.waiting;
      if (!worker) return true;
      
      // 发送跳过等待消息
      await new Promise((resolve, reject) => {
        const channel = new MessageChannel();
        channel.port1.onmessage = (msgEvent) => {
          if (msgEvent.data.error) {
            reject(msgEvent.data.error);
          } else {
            resolve(msgEvent.data);
          }
        };
        worker.postMessage({ type: 'skip-waiting' }, [channel.port2]);
      });

      clearCache();
      window.location.reload();
      return true;
    };

    // 显示更新通知
    const key = `open${Date.now()}`;
    const btn = (
      <Button
        type="primary"
        onClick={() => {
          notification.destroy(key);
          reloadSW();
        }}
      >
        {useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated.ok' })}
      </Button>
    );

    notification.open({
      message: useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated' }),
      description: useIntl().formatMessage({ id: 'app.pwa.serviceworker.updated.hint' }),
      btn,
      key,
      onClose: async () => null,
    });
  });
} 
// 在 HTTPS 环境但不启用 PWA 时，注销服务工作线程
else if ('serviceWorker' in navigator && isHttps) {
  const { serviceWorker } = navigator;
  
  // 注销所有注册的服务工作线程
  if (serviceWorker.getRegistrations) {
    serviceWorker.getRegistrations().then(sws => {
      sws.forEach(sw => sw.unregister());
    });
  }
  
  // 注销当前服务工作线程
  serviceWorker.getRegistration().then(sw => {
    if (sw) sw.unregister();
  });

  clearCache();
}
